<template>
    <video class="cmp cmp-hls" ref="video" :controls="true" controlslist=""></video>
</template>

<script>
let HLS = global.Hls || {}

export default {
  name: 'cmp-hls',
  props: {
    videoUrl: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
        hlsVideoObj: null,
    }
  },
  mounted () {
    this.$nextTick(() => {
        this.init()
    })
  },
  methods: {
    init () {
      if (!HLS.isSupported()) {
        console.log('当前浏览器不支持HLS.js')
        this.$toast('当前浏览器不支持HLS.js')
      }
    },
    // 播放
    play () {
        if (!this.$refs.video) return
        if (!this.videoUrl) {
            this.$toast('请输入视频地址')
            return
        }
        // if (/\.m3u8$/.test(this.videoUrl.split('?')[0])) {
        //     this.$toast('请输入m3u8格式的视频地址')
        //     return
        // }
        this.hlsVideoObj && this.hlsVideoObj.destroy()
        this.hlsVideoObj = new HLS()
        this.hlsVideoObj.attachMedia(this.$refs.video)
        this.hlsVideoObj.on(HLS.Events.MEDIA_ATTACHED, () => {
            console.log('video and hls.js are now bound together !')
            this.hlsVideoObj.loadSource(this.videoUrl)
            this.hlsVideoObj.on(HLS.Events.MANIFEST_PARSED, (e, data) => {
                console.log('manifest loaded,', e)
                console.log('manifest loaded, found ' + data.levels.length + ' quality level')
            })
        })
        this.hlsVideoObj.on(HLS.Events.ERROR, (e, data) => {
            console.log('error,', e, data)
            if (!data.fatal) return
            switch (data.type) {
                case HLS.ErrorTypes.NETWORK_ERROR:
                    console.log('fatal network error encountered, try to recover')
                    this.hlsVideoObj.startLoad()
                    break
                case HLS.ErrorTypes.MEDIA_ERROR:
                    console.log('fatal media error encountered, try to recover')
                    this.hlsVideoObj.recoverMediaError()
                    break
                default:
                    this.hlsVideoObj.destroy()
                    break
            }
        })
        this.$nextTick(() => {
            this.$refs.video.play()
        })
    },
    // 暂停
    pause () {
        this.$refs.video && this.$refs.video.pause()
    },
    // 销毁
    destroy () {
        this.hlsVideoObj && this.hlsVideoObj.destroy()
    }
  }
}
</script>

<style scoped lang="less">
@import "~@/assets/css/_mixins.less";
@import "~@/assets/css/_color.less";
.cmp-hls {
    display: block;
    width: 100%;
    height: 100%;
    background-color: #333;
}
</style>
